package com.baidu.ueditor.upload;

import com.baidu.ueditor.PathFormat;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.State;
import com.ruitaowang.core.utils.TimeUtils;
import com.ruitaowang.core.utils.aliyun.AliyunConfig;
import com.ruitaowang.core.utils.aliyun.OSSHelper;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class BinaryUploaderForOSS {

    Logger logger = LogManager.getLogger("BinaryUploaderForOSS");

    /**
     * create by neal.ma
     */
    public static final State save(HttpServletRequest request, Map<String, Object> conf) {
        boolean isAjaxUpload = request.getHeader("X_Requested_With") != null;
        String goodsId = request.getParameter("goodsId");
        String imageType = request.getParameter("imageType");
        String isActivity = request.getParameter("isActivity");
        if ((!StringUtils.hasLength(goodsId) || !StringUtils.hasLength(imageType)) && !StringUtils.hasLength(isActivity)) {
            return new BaseState(false, 5);
        }
        if (!ServletFileUpload.isMultipartContent(request)) {
            return new BaseState(false, 5);
        }
        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
        if (isAjaxUpload) {
            upload.setHeaderEncoding("UTF-8");
        }
        try {
            String now = TimeUtils.getCurrentDatetime(TimeUtils.TimeFormat.SHORT_DATE_PATTERN_SLASH);
            String savePath = "attached/file/" + now + "/";

            //重新命名文件名字
            String newFileName = "", fileExt = ".jpg", fileName = "";
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            //检查form中是否有enctype="multipart/form-data"
            if (multipartResolver.isMultipart(request)) {//将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                //获取multiRequest 中所有的文件名
                Iterator<String> it = multiRequest.getFileNames();
                //遍历文件
                while (it.hasNext()) {
                    MultipartFile file = multiRequest.getFile(it.next().toString());
                    if (file != null) {
                        //文件大小控制
                        fileName = file.getOriginalFilename();
                        if (fileName.lastIndexOf(".") != -1) {
                            fileExt = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
                        }
                        //新文件名称
                        String salt = TimeUtils.getCurrentDatetime(TimeUtils.TimeFormat.LONG_DATE_PATTERN_WITH_MILSEC_NONE_ORDER);
                        newFileName = savePath + salt + fileExt;
                        if (!validType(fileExt, (String[]) conf.get("allowFiles"))) {
                            return new BaseState(false, 8);
                        }
                        try {
                            //上传文件
                            OSSHelper.uploadToOSS(file.getInputStream(), newFileName);
                        } catch (IllegalStateException | IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            State storageState = new BaseState(Boolean.TRUE);
            if (storageState.isSuccess()) {
                storageState.putInfo("url", AliyunConfig.staticHost + PathFormat.format(newFileName));
                storageState.putInfo("type", fileExt);
                storageState.putInfo("original", fileName);
                storageState.putInfo("goodsId", goodsId);
                storageState.putInfo("imageType", imageType);
            }
            return storageState;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new BaseState(false, 4);
    }

    private static boolean validType(String type, String[] allowTypes) {
        List<String> list = Arrays.asList(allowTypes);
        return list.contains(type);
    }
}
